// 移动端菜单切换
const mobileMenuButton = document.getElementById('mobile-menu-button');
const mobileMenu = document.getElementById('mobile-menu');

mobileMenuButton.addEventListener('click', function() {
    mobileMenu.classList.toggle('hidden');
});

// 搜索相关元素
const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button');
const clearSearch = document.getElementById('clear-search');
const searchResults = document.getElementById('search-results');
const resultsContainer = document.getElementById('results-container');
const resultsHeading = document.getElementById('results-heading');
const closeResults = document.getElementById('close-results');
const helpCategories = document.getElementById('help-categories');

// 搜索映射数据库 - 包含更多详细信息，支持结果展示
const searchDatabase = [
    // 帮助中心相关
    {
        keywords: ["帮助", "帮助中心"],
        title: "帮助中心首页",
        description: "浏览所有帮助分类和常见问题",
        url: "help-center.html"
    },
    {
        keywords: ["常见问题", "问题解答", "faq"],
        title: "常见问题解答",
        description: "查看用户最常提问的问题和解决方案",
        url: "help-faq.html"
    },
    {
        keywords: ["客服", "支持", "联系我们"],
        title: "联系客服支持",
        description: "通过邮件、电话或在线聊天获取帮助",
        url: "help-center.html#contact"
    },
    
    // 账户相关
    {
        keywords: ["账户", "账号", "user account"],
        title: "账户管理",
        description: "管理您的UserHub账户设置和偏好",
        url: "help-account.html"
    },
    {
        keywords: ["注册", "新账户", "sign up"],
        title: "注册新账户",
        description: " step-by-step指南，帮助您创建UserHub账户",
        url: "help-account.html#register"
    },
    {
        keywords: ["登录", "sign in", "登录问题"],
        title: "账户登录",
        description: "如何登录您的UserHub账户及解决登录问题",
        url: "index.html"
    },
    {
        keywords: ["密码", "修改密码", "password"],
        title: "密码管理",
        description: "如何修改您的账户密码和密码安全建议",
        url: "help-account.html#password"
    },
    {
        keywords: ["忘记密码", "密码重置", "forgot password"],
        title: "忘记密码",
        description: "步骤指南，帮助您重置忘记的密码",
        url: "forgot-password.html"
    },
    {
        keywords: ["个人资料", "个人信息", "profile"],
        title: "个人资料设置",
        description: "如何查看和修改您的个人资料信息",
        url: "settings-profile.html"
    },
    {
        keywords: ["注销", "删除账户", "account deletion"],
        title: "账户注销",
        description: "如何永久删除您的UserHub账户",
        url: "help-account.html#delete"
    },
    
    // 任务相关
    {
        keywords: ["任务", "待办", "tasks", "todo"],
        title: "任务管理",
        description: "创建、管理和跟踪您的所有任务",
        url: "tasks.html"
    },
    {
        keywords: ["进行中", "in progress"],
        title: "进行中任务",
        description: "查看和管理所有正在进行的任务",
        url: "tasks.html?filter=in-progress"
    },
    {
        keywords: ["已完成", "completed"],
        title: "已完成任务",
        description: "查看所有已完成的任务历史记录",
        url: "tasks.html?filter=completed"
    },
    {
        keywords: ["创建任务", "new task"],
        title: "创建新任务",
        description: "如何创建和设置新任务的详细指南",
        url: "help-tasks.html#create"
    },
    {
        keywords: ["任务提醒", "reminder"],
        title: "任务提醒设置",
        description: "如何为任务设置提醒和截止日期",
        url: "help-tasks.html#reminder"
    },
    {
        keywords: ["分享任务", "任务协作", "share task"],
        title: "任务分享与协作",
        description: "如何将任务分享给其他用户并进行协作",
        url: "help-tasks.html#share"
    },
    {
        keywords: ["筛选任务", "排序任务", "filter tasks"],
        title: "任务筛选和排序",
        description: "如何根据不同条件筛选和排序任务列表",
        url: "help-tasks.html#filter"
    },
    
    // 消息相关
    {
        keywords: ["消息", "message", "对话"],
        title: "消息中心",
        description: "查看和管理您的所有消息和对话",
        url: "messages.html"
    },
    {
        keywords: ["通知", "notification", "提醒"],
        title: "通知中心",
        description: "查看所有系统和用户通知",
        url: "messages.html#notifications"
    },
    {
        keywords: ["未读", "unread"],
        title: "未读消息",
        description: "查看所有未读的消息和通知",
        url: "messages.html#unread"
    },
    {
        keywords: ["发送消息", "send message"],
        title: "发送消息",
        description: "如何向其他用户发送消息和文件",
        url: "messages.html"
    },
    
    // 设置相关
    {
        keywords: ["设置", "偏好", "settings"],
        title: "账户设置",
        description: "管理您的账户设置和偏好选项",
        url: "settings-profile.html"
    },
    {
        keywords: ["隐私", "隐私设置", "privacy"],
        title: "隐私设置",
        description: "管理您的个人信息和数据隐私选项",
        url: "settings-privacy.html"
    },
    {
        keywords: ["安全", "安全设置", "security"],
        title: "安全设置",
        description: "管理账户安全选项和二步验证",
        url: "settings-security.html"
    },
    {
        keywords: ["关于", "about"],
        title: "关于UserHub",
        description: "查看应用版本信息和相关资源",
        url: "settings-about.html"
    },
    {
        keywords: ["通知设置", "notification settings"],
        title: "通知偏好设置",
        description: "管理您接收通知的方式和内容",
        url: "settings-notifications.html"
    },
    
    // 集成服务
    {
        keywords: ["集成服务", "第三方服务", "integrations"],
        title: "集成服务管理",
        description: "管理与第三方服务的连接",
        url: "settings-integrations.html"
    },
    {
        keywords: ["google", "谷歌", "连接google"],
        title: "Google账户集成",
        description: "如何连接和使用Google账户集成功能",
        url: "settings-integrations.html#google"
    },
    {
        keywords: ["断开集成", "移除连接", "disconnect"],
        title: "断开集成服务",
        description: "如何断开与第三方服务的连接",
        url: "settings-integrations.html#disconnect"
    },
    {
        keywords: ["集成权限", "integration permissions"],
        title: "集成服务权限说明",
        description: "了解各集成服务所需的权限及用途",
        url: "help-center.html#integration-permissions"
    },
    
    // 其他页面
    {
        keywords: ["首页", "dashboard", "仪表盘"],
        title: "用户仪表盘",
        description: "UserHub的主页面，查看您的活动和概览",
        url: "dashboard.html"
    },
    {
        keywords: ["教程", "指南", "tutorial"],
        title: "使用教程",
        description: "详细的使用指南和视频教程",
        url: "tutorials.html"
    }
];

// 搜索输入框事件监听
searchInput.addEventListener('input', function() {
    // 显示/隐藏清除按钮
    if (this.value.trim()) {
        clearSearch.classList.remove('hidden');
    } else {
        clearSearch.classList.add('hidden');
        // 如果输入为空，隐藏搜索结果，显示分类
        searchResults.classList.add('hidden');
        helpCategories.classList.remove('hidden');
    }
});

// 处理回车键搜索
searchInput.addEventListener('keyup', function(e) {
    if (e.key === 'Enter' && this.value.trim()) {
        performSearch(this.value.trim());
    }
});

// 处理搜索按钮点击
searchButton.addEventListener('click', function() {
    if (searchInput.value.trim()) {
        performSearch(searchInput.value.trim());
    }
});

// 处理清除搜索按钮
clearSearch.addEventListener('click', function() {
    searchInput.value = '';
    clearSearch.classList.add('hidden');
    searchResults.classList.add('hidden');
    helpCategories.classList.remove('hidden');
});

// 处理关闭搜索结果
closeResults.addEventListener('click', function() {
    searchResults.classList.add('hidden');
    helpCategories.classList.remove('hidden');
});

// 执行搜索函数
function performSearch(query) {
    // 转换为小写便于匹配
    const lowerQuery = query.toLowerCase();
    const matchedResults = [];
    
    // 搜索匹配
    searchDatabase.forEach(item => {
        // 检查关键词是否匹配
        const isMatch = item.keywords.some(keyword => 
            keyword.toLowerCase().includes(lowerQuery) || 
            lowerQuery.includes(keyword.toLowerCase())
        );
        
        if (isMatch) {
            matchedResults.push(item);
        }
    });
    
    // 显示搜索结果
    displayResults(query, matchedResults);
}

// 显示搜索结果
function displayResults(query, results) {
    // 更新结果标题
    resultsHeading.textContent = `搜索 " ${query} " 的结果 (${results.length})`;
    
    // 清空之前的结果
    resultsContainer.innerHTML = '';
    
    if (results.length === 0) {
        // 没有找到结果
        resultsContainer.innerHTML = `
            <div class="text-center py-8">
                <i class="fa fa-search text-gray-300 text-4xl mb-4"></i>
                <p class="text-gray-500 mb-4">未找到与"${query}"相关的内容</p>
                <p class="text-gray-400 text-sm">请尝试其他关键词，如"账户"、"任务"或"消息"</p>
            </div>
        `;
    } else {
        // 显示找到的结果
        const resultsList = document.createElement('ul');
        resultsList.className = 'space-y-4';
        
        results.forEach(item => {
            const listItem = document.createElement('li');
            listItem.className = 'pb-4 border-b border-gray-100 last:border-0 last:pb-0';
            
            listItem.innerHTML = `
                <h3 class="font-medium mb-1">
                    <a href="${item.url}" class="text-primary hover:underline">${item.title}</a>
                </h3>
                <p class="text-gray-600 text-sm mb-2">${item.description}</p>
                <div class="text-xs text-gray-400">
                    <span>${item.url}</span>
                </div>
            `;
            
            resultsList.appendChild(listItem);
        });
        
        resultsContainer.appendChild(resultsList);
    }
    
    // 显示搜索结果，隐藏分类
    searchResults.classList.remove('hidden');
    helpCategories.classList.add('hidden');
}

// 设置当前日期和用户信息
document.addEventListener('DOMContentLoaded', function() {
    // 获取当前日期并显示
    const dateOptions = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
    const currentDate = new Date().toLocaleDateString('zh-CN', dateOptions);
    if (document.getElementById('current-date')) {
        document.getElementById('current-date').textContent = currentDate;
    }
    
    // 获取当前登录用户信息
    const users = JSON.parse(localStorage.getItem('registeredUsers')) || [];
    const loginEmail = localStorage.getItem('currentLoginEmail');
    
    // 验证用户是否已登录
    if (!loginEmail) {
        // 如果没有登录信息，跳转到登录页
        window.location.href = 'index.html';
        return;
    }
    
    // 查找当前登录用户
    const currentUser = users.find(user => user.email === loginEmail);
    
    if (currentUser) {
        // 显示用户名到页面各处
        if (document.getElementById('welcome-username')) {
            document.getElementById('welcome-username').textContent = currentUser.name;
        }
        if (document.getElementById('user-display-name')) {
            document.getElementById('user-display-name').textContent = currentUser.name;
        }
    } else {
        // 如果用户不存在，清除登录状态并跳转到登录页
        localStorage.removeItem('currentLoginEmail');
        window.location.href = 'index.html';
    }
    
    // 用户菜单下拉功能
    const userMenuButton = document.getElementById('user-menu-button');
    const userMenuDropdown = document.getElementById('user-menu-dropdown');
    
    // 点击头像切换菜单显示/隐藏
    userMenuButton.addEventListener('click', function(event) {
        event.stopPropagation(); // 防止事件冒泡
        userMenuDropdown.classList.toggle('hidden');
    });
    
    // 点击页面其他地方关闭菜单
    document.addEventListener('click', function(event) {
        if (!userMenuButton.contains(event.target) && !userMenuDropdown.contains(event.target)) {
            userMenuDropdown.classList.add('hidden');
        }
    });
    
    // 退出登录功能
    document.getElementById('logout-button').addEventListener('click', function() {
        localStorage.removeItem('currentLoginEmail');
        window.location.href = 'index.html';
    });
    
    // 移动端菜单切换
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const mobileMenu = document.getElementById('mobile-menu');
    
    mobileMenuButton.addEventListener('click', function() {
        mobileMenu.classList.toggle('hidden');
    });
    
    // 更新头像
    updateAvatar();
    
    // 监听头像更新事件
    window.addEventListener('avatarUpdated', function(e) {
        const headerAvatar = document.getElementById('header-avatar');
        if (headerAvatar) {
            headerAvatar.src = e.detail.avatar;
        }
    });
    
    // 监听本地存储变化（应对多标签页情况）
    window.addEventListener('storage', function(e) {
        if (e.key === 'registeredUsers') {
            updateAvatar();
        }
    });
});

// 更新头像的函数
function updateAvatar() {
    const users = JSON.parse(localStorage.getItem('registeredUsers')) || [];
    const loginEmail = localStorage.getItem('currentLoginEmail');
    const currentUser = users.find(user => user.email === loginEmail);
    
    const headerAvatar = document.getElementById('header-avatar');
    if (currentUser && currentUser.avatar && headerAvatar) {
        headerAvatar.src = currentUser.avatar;
    }
}
